package com.ds.infrastructure.audit.collector.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ds.infrastructure.audit.collector.config.KafkaProperty;
import com.ds.infrastructure.audit.collector.constant.CollectorConstant;
import com.ds.infrastructure.audit.collector.entity.App;
import com.ds.infrastructure.audit.collector.entity.RateAccess;
import com.ds.infrastructure.audit.collector.service.IAppService;
import com.ds.infrastructure.audit.collector.service.IMessageService;
import com.ds.infrastructure.audit.collector.service.IRateService;
import com.ds.infrastructure.audit.collector.service.MessageThreadFactory;
import com.ds.infrastructure.audit.common.constant.CommonConstant;
import com.ds.infrastructure.audit.common.entity.KbaBehavior;
import com.ds.infrastructure.audit.common.entity.KbaBehaviorWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 作用：
 *
 * @author WeiShaoying
 * @date 2020/7/31
 */
@Service
@Slf4j
public class MessageServiceImpl implements IMessageService {

    @Resource
    private IRateService rateService;

    private final IAppService appService;

    private final KafkaTemplate<String, String> kafkaTemplate;

    private ExecutorService executorService;

    @Value("${collector.limit:false}")
    private boolean enableLimit;

    @Value("${collector.auth:true}")
    private boolean enableAuth;

    @Value("${search-platform.topic}")
    private String searchTopic;

    @Value("${search-platform.key}")
    private String searchKey;

    @Autowired
    private KafkaProperty kafkaProperty;

    private static KafkaProducer<String, String> kafkaProducer;


    public MessageServiceImpl(KafkaTemplate<String, String> kafkaTemplate, IAppService appService) {
        this.kafkaTemplate = kafkaTemplate;
        this.appService = appService;
    }

    @PostConstruct
    private void init() {
        log.info("EnableLimit={}", enableLimit);
        log.info("EnableAuth={}", enableAuth);
        log.info("SearchTopic={}", searchTopic);
        log.info("SearchKey={}", searchKey);
        executorService = new ThreadPoolExecutor(5, 200, 100, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(200000),
                new MessageThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());

        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaProperty.getProducerBroker());
        props.put(ProducerConfig.RETRIES_CONFIG, 0);
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
        props.put(ProducerConfig.LINGER_MS_CONFIG, 100);
        props.put(ProducerConfig.ACKS_CONFIG, "all");
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
        props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, 1);//只有一个连接向broker发送数据
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        kafkaProducer = new KafkaProducer<>(props);
        log.info("==KafkaProducer={}", props.toString());
    }

    /**
     * Message Process
     *
     * @param wrapperList
     */
    @Override
    public void process(List<KbaBehaviorWrapper> wrapperList) {
        if (CollectionUtils.isEmpty(wrapperList)) {
            return;
        }
        //验证是否需要检验所有的
        KbaBehaviorWrapper wrapper0 = wrapperList.get(0);
        String appName = wrapper0.getAppName();
        String appKey = wrapper0.getAppKey();
        String key = appService.getKey(appName, appKey);

        //如果需要开启权限验证
        if (enableAuth) {
            boolean registeredApp = appService.isRegisteredApp(appName, appKey);
            if (registeredApp) {
                if (enableLimit) {
                    App app = appService.queryByCondition(appName, appKey);
                    if (app != null && app.getSpeedLimit() > 0) {
                        boolean b = rateService.canAccess(RateAccess.of(CollectorConstant.KEY_KBATRACK_RATE_LIMIT, key, 1, app.getSpeedLimit()));
                        if (!b) {
                            log.warn("Rate Limit :: {}", appName);
                            return;
                        }
                    }
                }
            } else {
                log.warn("{}::{}", CollectorConstant.APP_NO_REGISTER, key);
                //TODO: 发送短信,微信 告警
                return;
            }
        }
        for (KbaBehavior behavior : wrapperList) {
            executorService.submit(() -> send(behavior));
        }
    }


    @Override
    public void processSingle(KbaBehaviorWrapper wrapper) {
        //如果需要开启权限验证
        if (enableAuth) {
            String appName = wrapper.getAppName();
            String appKey = wrapper.getAppKey();
            String key = appService.getKey(appName, appKey);
            boolean registeredApp = appService.isRegisteredApp(appName, appKey);
            if (registeredApp) {
                if (enableLimit) {
                    App app = appService.queryByCondition(appName, appKey);
                    if (app != null && app.getSpeedLimit() > 0) {
                        boolean b = rateService.canAccess(RateAccess.of(CollectorConstant.KEY_KBATRACK_RATE_LIMIT, key, 1, app.getSpeedLimit()));
                        if (!b) {
                            log.warn("Rate Limit :: {}", appName);
                            return;
                        }
                    }
                }
            } else {
                log.warn("{}::{}", CollectorConstant.APP_NO_REGISTER, key);
                return;
            }
        }
        executorService.submit(() -> send(wrapper));
    }


    private void send(KbaBehavior behavior) {
        //log.debug("==接受到：{}", behavior);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(CollectorConstant.APP_KEY, searchKey);
        jsonObject.put(CollectorConstant.TYPE, CommonConstant.TOPIC_MSG_COLLECTOR);
        jsonObject.put("data", behavior);
        kafkaTemplate.send(searchTopic, jsonObject.toJSONString());
        //kafkaProducer.send(new ProducerRecord(searchTopic, jsonObject.toJSONString()));
    }


}
